# -*- coding: utf-8 -*-
##zixue@taobao.com
##2008-9-3

import cgi
import os
import string
import time
import wsgiref.handlers

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import memcache

from AppListDemo import *
from TbApi import *
from HttpClient import HttpClient
from AEProxy import *
from Log import Log
Log.enableDebug = True


config = ApiConfig.all()[0]
Log.info('Fetched ApiConfig from db.')
api = TbApi(config)
api.httpClient = HttpClient(AEHttp())

class ItemInstockController(webapp.RequestHandler):
	app_path = '/item/instock'

	def get(self):
		user = checkLogin(self, self.app_path)
		if user is None: return
		rs =  api.getInstockItems('title,price,num,seller_cids', user.nickname())
		items = None
		msg = None
		url = None
		page_redirect = None
		if(rs.isSuccess()):
			items = rs.rsp
		else:
			msg = rs.msg
			if(rs.code == 1004):
				url = getSipLoginUrl(rs.url, self.request.url)
				page_redirect = getPageRedirect(url)
		template_values = {
			'page_header':getPageHeader(user.nickname(),users.create_logout_url(self.app_path)),
			'page_title':'仓库内的宝贝',
			'login':user,
			'items':items,
			'msg':msg,
			'url':url,
			'page_redirect':page_redirect
		}
		path = os.path.join(os.path.dirname(__file__), 'ItemInstock.html')
		self.response.out.write(template.render(path, template_values))

class ItemOnsaleController(webapp.RequestHandler):
	app_path = '/item/onsale'

	def get(self):
		user = checkLogin(self, self.app_path)
		if user is None: return
		rs =  api.getOnsaleItems('title,price,num,seller_cids', user.nickname())
		items = None
		msg = None
		url = None
		page_redirect = None
		if(rs.isSuccess()):
			items = rs.rsp
		else:
			msg = rs.msg
			if(rs.code == 1004):
				url = getSipLoginUrl(rs.url, self.request.url)
				page_redirect = getPageRedirect(url)
		template_values = {
			'page_header':getPageHeader(user.nickname(),users.create_logout_url(self.app_path)),
			'page_title':'出售中的宝贝',
			'login':user,
			'items':items,
			'msg':msg,
			'url':url,
			'page_redirect':page_redirect
		}
		path = os.path.join(os.path.dirname(__file__), 'ItemOnsale.html')
		self.response.out.write(template.render(path, template_values))


def main():
	application = webapp.WSGIApplication(
                                       [(ItemInstockController.app_path, ItemInstockController),
				       (ItemOnsaleController.app_path, ItemOnsaleController)])
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()